<template>
  <div class="article-manager-container">
    <div class="article-header">
      <!-- <h2 class="article-title">
        <i class="fas fa-book-open header-icon" style="color: #3998a9;"></i>
        文章管理
      </h2> -->
      <h2 style="color: #3998a9;">文章管理</h2>
      <div class="action-buttons">
        <el-button type="primary" @click="goToEditPage()" class="add-btn">
          <i class="fas fa-plus"></i> 添加文章
        </el-button>
        <el-button type="success" @click="refreshList" class="refresh-btn" :loading="loading">
          <i class="fas fa-sync-alt"></i> 刷新列表
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="searchForm" inline>
        <el-form-item label="文章标题">
          <el-input v-model="searchForm.title" placeholder="请输入文章标题" clearable @keyup.enter="handleSearch"
            style="width: 200px" />
        </el-form-item>
        <el-form-item label="文章分类">
          <el-popover placement="bottom-start" :width="300" trigger="click" v-model:visible="categoryPopoverVisible">
            <template #reference>
              <el-input v-model="selectedCategoryName" placeholder="请选择分类" readonly style="width: 200px">
                <template #suffix>
                  <el-icon>
                    <ArrowDown />
                  </el-icon>
                </template>
              </el-input>
            </template>

            <div class="category-tree-container">
              <div class="tree-header">
                <span>选择分类</span>
                <el-button type="text" size="small" @click="clearCategorySelection">
                  清除选择
                </el-button>
              </div>
              <el-tree ref="categoryTreeRef" :data="categoryTreeData" :props="treeProps" node-key="id"
                :highlight-current="true" :expand-on-click-node="false" @node-click="handleCategorySelect"
                class="category-tree">
                <template #default="{ node, data }">
                  <span class="custom-tree-node">
                    <span :class="{ 'category-name': true, 'inactive': !data.isActive }">
                      {{ node.label }}
                    </span>
                    <span v-if="!data.isActive" class="inactive-badge">已禁用</span>
                  </span>
                </template>
              </el-tree>
            </div>
          </el-popover>
        </el-form-item>
        <el-form-item label="文章状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="草稿" :value="0" />
            <el-option label="已发布" :value="1" />
            <el-option label="已下线" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <i class="fas fa-search"></i> 搜索
          </el-button>
          <el-button @click="handleReset">
            <i class="fas fa-refresh"></i> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="article-list-container">
      <el-table :data="articles" style="width: 100%" v-loading="loading" empty-text="暂无数据">
        <el-table-column prop="title" label="文章标题" width="300">
          <template #default="{ row }">
            <div class="article-title-cell">
              <i :class="row.starred ? 'fas fa-star' : 'fas fa-file-alt'" class="article-icon"></i>
              <span>{{ row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="分类" width="120">
          <template #default="{ row }">
            <el-tag :type="getTagType(row.categoryName)">
              {{ row.categoryName || '未分类' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="tags" label="标签" width="180">
          <template #default="{ row }">
            <div class="tags-container">
              <el-tag v-for="tag in getTagsArray(row.tags)" :key="tag" size="small" class="tag-item" type="info">
                {{ tag.trim() }}
              </el-tag>
              <span v-if="!row.tags || row.tags.trim() === ''" class="no-tags">
                无标签
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建日期" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <div class="action-btns-container">
              <el-button size="small" @click.stop="goToEditPage(row)" class="action-btn edit-btn" plain>
                <i class="fas fa-edit"></i> 编辑
              </el-button>
              <el-button v-if="row.status === 0" size="small" @click.stop="publishArticle(row)"
                class="action-btn publish-btn" plain>
                <i class="fas fa-upload"></i> 发布
              </el-button>
              <el-button v-if="row.status === 1" size="small" @click.stop="offlineArticle(row)"
                class="action-btn offline-btn" plain>
                <i class="fas fa-arrow-down"></i> 下线
              </el-button>
              <el-popconfirm title="确定要删除这篇文章吗？" @confirm="deleteArticleHandler(row)">
                <template #reference>
                  <el-button size="small" @click.stop class="action-btn delete-btn" plain>
                    <i class="fas fa-trash-alt"></i> 删除
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.pageIndex" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import {
  getArticleList,
  queryArticles,
  deleteArticle,
  updateArticleStatus,
  getArticleCategoryTree
} from '@/api/article'
// import { useAuthStore } from '@/stores/authStore'

const router = useRouter()
// const authStore = useAuthStore()
// const userId = authStore.user?.id

// 响应式数据
const articles = ref([])
const loading = ref(false)

// 分类树相关
const categoryTreeRef = ref(null)
const categoryPopoverVisible = ref(false)
const categoryTreeData = ref([])
const selectedCategoryName = ref('')

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'articleCategoryName'
}

// 搜索表单
const searchForm = ref({
  title: '',
  categoryId: null,
  status: null
})

// 分页数据
const pagination = ref({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 获取文章列表
const loadArticles = async (isSearch = false) => {
  loading.value = true
  try {
    let response
    if (isSearch) {
      // 条件查询
      response = await queryArticles({
        ...searchForm.value,
        pageIndex: pagination.value.pageIndex,
        pageSize: pagination.value.pageSize
      })
    } else {
      // 获取分页列表
      response = await getArticleList({
        pageIndex: pagination.value.pageIndex,
        pageSize: pagination.value.pageSize
      })
    }

    if (response.code === 200) {
      articles.value = response.data.items.map(article => ({
        id: article.id,
        title: article.title,
        categoryName: article.categoryName || '未分类',
        tags: article.tags || '',
        status: article.status, // 0: 草稿, 1: 已发布, 2: 已下线
        createdAt: article.createdAt,
        starred: false // 可以根据需要添加星标功能
      }))
      pagination.value.total = response.data.totalCount
    } else {
      ElMessage.error(response.message || '获取文章列表失败')
    }
  } catch (error) {
    console.error('获取文章列表失败:', error)
    ElMessage.error('获取文章列表失败: ' + (error.message || '网络错误'))
  } finally {
    loading.value = false
  }
}

// 获取分类树
const loadCategories = async () => {
  try {
    // 修改：只获取启用的分类，用于搜索
    const response = await getArticleCategoryTree(true) // 传递 true 表示只获取启用的分类
    if (response.code === 200) {
      categoryTreeData.value = response.data || []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 处理分类选择
const handleCategorySelect = (data) => {
  // 由于只加载了启用的分类，这里不需要再检查 isActive
  searchForm.value.categoryId = data.id
  selectedCategoryName.value = data.articleCategoryName
  categoryPopoverVisible.value = false

  // 高亮选中的节点
  categoryTreeRef.value?.setCurrentKey(data.id)
}

// 清除分类选择
const clearCategorySelection = () => {
  searchForm.value.categoryId = null
  selectedCategoryName.value = ''
  categoryTreeRef.value?.setCurrentKey(null)
}

// 删除文章
const deleteArticleHandler = async (article) => {
  try {
    const response = await deleteArticle(article.id)
    if (response.code === 200) {
      ElMessage.success(`${article.title} 已删除`)
      await loadArticles() // 重新加载列表
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    console.error('删除文章失败:', error)
    ElMessage.error('删除失败: ' + (error.message || '网络错误'))
  }
}

// 发布文章
const publishArticle = async (article) => {
  try {
    const response = await updateArticleStatus(article.id, 1)
    if (response.code === 200) {
      ElMessage.success(`${article.title} 已发布`)
      await loadArticles() // 重新加载列表
    } else {
      ElMessage.error(response.message || '发布失败')
    }
  } catch (error) {
    console.error('发布文章失败:', error)
    ElMessage.error('发布失败: ' + (error.message || '网络错误'))
  }
}

// 下线文章
const offlineArticle = async (article) => {
  try {
    const response = await updateArticleStatus(article.id, 2)
    if (response.code === 200) {
      ElMessage.success(`${article.title} 已下线`)
      await loadArticles() // 重新加载列表
    } else {
      ElMessage.error(response.message || '下线失败')
    }
  } catch (error) {
    console.error('下线文章失败:', error)
    ElMessage.error('下线失败: ' + (error.message || '网络错误'))
  }
}

// 搜索
const handleSearch = async () => {
  pagination.value.pageIndex = 1 // 重置到第一页
  await loadArticles(true)
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    title: '',
    categoryId: null,
    status: null
  }
  selectedCategoryName.value = ''
  categoryTreeRef.value?.setCurrentKey(null)
  pagination.value.pageIndex = 1
  loadArticles()
}

// 刷新列表
const refreshList = async () => {
  await loadArticles()
  ElMessage.success('列表已刷新')
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  pagination.value.pageIndex = 1
  loadArticles()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.value.pageIndex = page
  loadArticles()
}

// 状态转换
const getStatusText = (status) => {
  const statusMap = {
    0: '草稿',
    1: '已发布',
    2: '已下线'
  }
  return statusMap[status] || '未知'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 分类映射（从API获取）
// const categoryMap = computed(() => {
//   const map = {}
//   categories.value.forEach(category => {
//     map[category.articleCategoryName] = category.articleCategoryName
//   })
//   return map
// })

// 获取标签类型
const getTagType = (category) => {
  const typeMap = {
    '技术': 'primary',
    '生活': 'success',
    '教育': 'warning',
    '财经': 'danger',
    '娱乐': 'info'
  }
  return typeMap[category] || 'info' // 改为返回 'info' 而不是空字符串
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    0: 'warning', // 草稿
    1: 'success', // 已发布
    2: 'danger'   // 已下线
  }
  return typeMap[status] || 'info'
}

// 获取标签数组
const getTagsArray = (tags) => {
  if (!tags || tags.trim() === '') {
    return []
  }
  return tags.split(',').filter(tag => tag.trim() !== '')
}

// 跳转到编辑页面
const goToEditPage = (article = null) => {
  if (article) {
    router.push({
      name: 'ArticleAddorEdit',
      params: { id: article.id },
      query: {
        title: article.title,
        category: article.categoryName,
        status: article.status
      }
    })
  } else {
    router.push({ name: 'ArticleAddorEdit' })
  }
}

// 页面加载时获取数据
onMounted(async () => {
  await Promise.all([
    loadArticles(),
    loadCategories()
  ])
})
</script>

<style scoped>
/* 保持原有样式不变 */
.article-manager-container {
  padding: 25px;
  background-color: #f8fafc;
  min-height: calc(100vh - 60px);
}

.article-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding: 18px 25px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
}

.article-title {
  margin: 0;
  font-size: 22px;
  color: #2c3e50;
  display: flex;
  align-items: center;
  font-weight: 600;
}

.header-icon {
  margin-right: 12px;
  color: #409EFF;
  font-size: 1.2em;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.add-btn,
.refresh-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 18px;
  font-weight: 500;
  border-radius: 8px;
}

/* 搜索区域样式 */
.search-container {
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
}

.article-list-container {
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
}

.article-title-cell {
  display: flex;
  align-items: center;
  gap: 10px;
}

.article-icon {
  font-size: 18px;
  color: #606266;
}

.article-icon.fa-star {
  color: #F56C6C;
}

.action-btns-container {
  display: flex;
  gap: 8px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 7px 12px;
  border-radius: 6px;
  font-weight: 500;
}

.edit-btn {
  color: #409EFF;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}

.publish-btn {
  color: #67C23A;
  border-color: #c2e7b0;
  background-color: #f0f9ff;
}

.offline-btn {
  color: #E6A23C;
  border-color: #f5dab1;
  background-color: #fdf6ec;
}

.delete-btn {
  color: #F56C6C;
  border-color: #fde2e2;
  background-color: #fef0f0;
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 分类树相关样式 */
.category-tree-container {
  max-height: 300px;
  overflow-y: auto;
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 8px;
  font-weight: 500;
}

.category-tree {
  max-height: 250px;
  overflow-y: auto;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.category-name {
  flex: 1;
}

.category-name.inactive {
  color: #c0c4cc;
}

.inactive-badge {
  font-size: 12px;
  color: #f56c6c;
  background-color: #fef0f0;
  padding: 2px 6px;
  border-radius: 4px;
  margin-left: 8px;
}

/* 标签相关样式 */
.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  align-items: center;
}

.tag-item {
  margin: 0;
  font-size: 12px;
}

.no-tags {
  color: #c0c4cc;
  font-size: 12px;
  font-style: italic;
}
</style>